const express = require('express');
const router = express.Router();
const { Category, Course } = require('../../models')
const { Op } = require('sequelize')
const { success, failure } = require('../../utils/responses');
const{NotFoundError}=require('../../utils/errors')

//查询分类列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        // 当前页数，如果不传值默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        // 每页显示的数量，如果不传值默认10
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        //计算offset
        const offset = (currentPage - 1) * pageSize

        const condition = {
            order: [['rank', 'ASC'], ['id', 'ASC']],
            limit: pageSize,
            offset: offset
        }

        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            }
        }

        const { count, rows } = await Category.findAndCountAll(condition)
        success(res, '分类查询成功', {
            categories: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error)
    }

})
//查询分类详情
router.get('/:id', async function (req, res) {
    try {
        const category = await getCategory(req)
        success(res, '查询分类成功', { category })

    } catch (error) {
        failure(res, error)
    }

})

//创建分类
router.post('/', async function (req, res) {
    try {
        //创建白名单过滤
        const body = filterBody(req)
        const category = await Category.create(body);
        //200和201都表示成功,201表示创建新的资源
        success(res, '创建分类成功', { category }, 201)
    } catch (error) {
        failure(res, error)
    }
})

//删除分类
router.delete('/:id', async function (req, res) {
    try {
        const category = await getCategory(req)
        const count = await Course.count({ where: { categoryId: req.params.id } })
        // if (count>0) {
        //     throw new Error('该分类下存在课程，不能删除')
        // }
        // await category.destroy()
        // success(res, '删除分类成功')
        res.json({
            message:count
        })
    } catch (error) {
        failure(res, error)
    }
})

//更新分类
router.put('/:id', async function (req, res) {
    try {
        const category = await getCategory(req)

        //创建白名单过滤
        const body = filterBody(req)

        //更新分类
        await category.update(body)
        success(res, '更新分类成功', { category })

    } catch (error) {
        failure(res, error)
    }
})

//查询当前分类：公共方法
async function getCategory(req) {
    //获取分类ID
    const { id } = req.params
    //查询当前分类ID
    const category = await Category.findByPk(id)

    //如果分类不存在，抛出错误异常
    if (!category) {
        throw new NotFoundError(`ID:${id}分类不存在`)
    }
    return category
}

// 白名单过滤：公共方法
function filterBody(req) {
    return {
        name: req.body.name,
        rank: req.body.rank,
    }
}
module.exports = router;